package com.keyidea.jfxui.core.server.job;

import com.keyidea.jfxui.core.util.MemStorage;
import com.keyidea.jfxui.portal.view.server.test.ComponentTestView;
import com.keyidea.jfxui.portal.view.server.test.ComponentTestViewModel;
import de.saxsys.mvvmfx.FluentViewLoader;
import de.saxsys.mvvmfx.ViewTuple;
import javafx.application.Platform;
import javafx.scene.Parent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 动态消息输出（减少javaFX控件的刷新频率）
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class DynamicMessagePrintJob {
    /**
     * 判断javafx控件是否加载成功
     */
    private static int IS_LOADING = 0;

    public void startUp() {
        ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(
                1,
                new BasicThreadFactory.Builder().namingPattern("dynamic-message-print-schedule-pool-%d").daemon(true).build());
        ses.scheduleAtFixedRate(
                () -> {
                    try {
                        List<String> list = new ArrayList<>();
                        MemStorage.REDIS_MESSAGE_LIST.drainTo(list);
                        if (!CollectionUtils.isEmpty(list)) {
                            ViewTuple<ComponentTestView, ComponentTestViewModel> viewTuple = FluentViewLoader.fxmlView(ComponentTestView.class).load();
                            ComponentTestView codeBehind = viewTuple.getCodeBehind();
                            // redis消息不为空，析出全部输出到javaFX的redis消息池
                            Platform.runLater(() -> codeBehind.getRedisLogArea().appendText(String.join("，", list)));
                        }
                        // 加载成功后置为1
                        if (IS_LOADING == 0) {
                            IS_LOADING = 1;
                        }
                    } catch (Exception e) {
                        IS_LOADING = 0;
                        log.warn("FXMLLoader 加载失败……");
                    }
                    if (IS_LOADING == 1) {
                        log.warn("FXMLLoader 加载成功……");
                        // 加载成功后不在，置位2不在判断
                        IS_LOADING = 2;
                    }
                }, 1, 1, TimeUnit.SECONDS);
    }
}
